from vec import Vec2
import math
import pgzrun
import random
WIDTH = 500
HEIGHT = 500

PEN_COLOR = (0, 200, 0)
BACK_COLOR = (0, 0, 0)
ptList=[]
length=400
pt_mid=Vec2(WIDTH/2,HEIGHT/2)
y_offset=length/math.sqrt(3)

pt_a=Vec2(pt_mid.x,pt_mid.y-y_offset)
pt_d=Vec2(pt_mid.x,pt_mid.y+length/2/math.sqrt(3))
pt_b=Vec2(pt_d.x-length/2,pt_d.y)
pt_c=Vec2(pt_d.x+length/2,pt_d.y)

ptList.append(pt_a)
ptList.append(pt_b)
ptList.append(pt_c)

def fractal(ptList):
    i=0
    while True:
        if(i==len(ptList)-1):
            lf(ptList,i,0)            
            break
        else:
            i=lf(ptList,i,i+1)

def lf(ptList,a,b):
    pt1=ptList[a]*2/3+ptList[b]/3
    midPt=(ptList[a]+ptList[b])/2
    dir=ptList[b]-ptList[a]
    dir.normalize()
    vdir=Vec2(0,0)
    n=random.randint(1,100)
    if(n<=100):
        vdir.x=-dir.y
        vdir.y=dir.x
    else: 
        vdir.x=dir.y
        vdir.y=-dir.x
    dist=(ptList[b]-ptList[a]).length()/3/2*math.sqrt(3)
    pt2=midPt+vdir*dist
    pt3=ptList[a]/3+ptList[b]*0.666
    ptList.insert(a+1,pt3)
    ptList.insert(a+1,pt2)
    ptList.insert(a+1,pt1)
    return a+4

for i in range(5):
    fractal(ptList)

def draw():
    screen.fill(BACK_COLOR)
    for i in range(len(ptList)):
        if i==len(ptList)-1:
            screen.draw.line(ptList[i].raw_get(), ptList[0].raw_get(), PEN_COLOR)            
        else:
            screen.draw.line(ptList[i].raw_get(), ptList[i + 1].raw_get(), PEN_COLOR)
pgzrun.go()